package io.renren.modules.api.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import io.renren.common.exception.RRException;
import io.renren.common.utils.*;
import io.renren.modules.api.annotation.LoginDriver;
import io.renren.modules.api.entity.PsOrderLogisticsRecordEntity;
import io.renren.modules.api.entity.SjTixianEntity;
import io.renren.modules.api.service.PsOrderLogisticsRecordService;
import io.renren.modules.api.service.PsOrderRouteSectionService;
import io.renren.modules.api.service.SjTixianService;
import io.renren.modules.api.service.UserService;
import io.renren.modules.driver.entity.PsParamSetEntity;
import io.renren.modules.driver.entity.SjDriverEntity;
import io.renren.modules.driver.service.PsParamSetService;
import io.renren.modules.driver.service.SjDriverService;
import io.renren.modules.psorder.entity.PsOrderEntity;
import io.renren.modules.psorder.service.PsOrderService;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 司机强相关性接口
 * Created by WDJ on 2017/12/4.
 */
@RestController
@RequestMapping("/driver")
public class ApiDriverController {

    @Autowired
    private SjDriverService driverService;
    @Autowired
    private PsOrderService psOrderService;
    @Autowired
    private UserService userService;
    @Autowired
    private SjTixianService sjTixianService;
    @Autowired
    private PsOrderRouteSectionService psOrderRouteSectionService;
    @Autowired
    private PsOrderLogisticsRecordService psOrderLogisticsRecordService;
    @Autowired
    private PsParamSetService psParamSetService;

    @Value("${qwj.imagesPath}")
    String ROOT;

    @Value("${qwj.psOrderImagesPath}")
    String ROOT_PsImages;

    /**
     * 获取司机个人信息
     * @param driver
     * @return
     */
    @GetMapping("driverInfo")
    public R driverInfo(@LoginDriver SjDriverEntity driver){
        return R.ok().put("driver", driver);
    }

    /**
     * 司机修改车型接口
     */
    @PostMapping("modifyCarStyle")
    public R modifyCarStyle(@LoginDriver SjDriverEntity driver,String carstyle){
        driver.setCarno(carstyle);
        driverService.update(driver);
        return R.ok();
    }

    /**
     * 司机更新registrationId
     */
    @PostMapping("updateDriverRegId")
    public R updateDriverRegId(@LoginDriver SjDriverEntity driver,String registrationId){
        String regId = driver.getRegistrationId();
        if (regId != null && !regId.equals(registrationId)) {
            driver.setRegistrationId(registrationId);
            driverService.update(driver);
        } else {
            return R.error(-1,"registrationId本来为null或者无需更新!");
        }

        return R.ok("更新成功!");
    }

    /**
     * 司机出车,可以开始接单
     * @param driver
     * @param longitude 经度
     * @param latitude  纬度
     * @param address   地址城
     * @param registrationId 极光Id
     * @return
     */
    @PostMapping("dispatchCar")
    public R dispatchCar(@LoginDriver SjDriverEntity driver,String longitude, String latitude, String address, String registrationId){
        if (registrationId == null || "".equals(registrationId)) {
            return R.error(-1,"传的registrationId为null或空串!");
        }
        if(driver.getDriveStatus() != null && !"0".equals(driver.getDriveStatus())) {
            if("1".equals(driver.getDriveStatus())){
                return R.error(-2,"司机已经出车!");
            } else if("2".equals(driver.getDriveStatus())) {
                return R.error(-3,"订单进行中!");
            }
        }

        //待插入表数据参数拼接
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("_name", driver.getUsername());
        map.put("_location", longitude + "," + latitude);
        map.put("_address", address);
        JSONObject jsonObject = JSONObject.fromObject(map);

        String paraForSign = "data=" + jsonObject.toString() + "&key=" + QwjGlobal.AUTONAVI_WEB_KEY + "&tableid=" + QwjGlobal.AUTONAVI_HTTP_TABLE_ID
                + QwjGlobal.AUTONAVI_WEB_PRIVATE_KEY;
        String sig = MD5Util.MD5Encode(paraForSign, "utf-8");

        Map<String, String> paraMap = new HashMap<String, String>();
        paraMap.put("data", jsonObject.toString());
        paraMap.put("key", QwjGlobal.AUTONAVI_WEB_KEY);
        paraMap.put("tableid", QwjGlobal.AUTONAVI_HTTP_TABLE_ID);
        paraMap.put("sig", sig);

        //发送 POST 请求
        String sr = HttpUtil.sendPost(QwjGlobal.AUTONAVI_HTTP_DATA_CREATE_URL, paraMap);
        Map<String, Object> resultMap = QmJsonUtils.parseJSON2Map(sr);
        int status = Integer.valueOf(String.valueOf(resultMap.get("status"))).intValue();
        if (status == 1) {
            String gaoId = String.valueOf(resultMap.get("_id"));
            driver.setGaoId(gaoId);
            driver.setDriveStatus("1"); //设置1代表出车，等待订单状态
            driver.setRegistrationId(registrationId);
            driverService.update(driver);

            return R.ok("出车成功!");
        } else {
            return R.error(-4,"插入高德数据失败!");
        }

    }

    /**
     * 实时更新司机位置
     * @param driver
     * @param longitude
     * @param latitude
     * @param address
     * @return
     */
    @PostMapping("realTimeLocation")
    public R realTimeLocation(@LoginDriver SjDriverEntity driver,String longitude, String latitude, String address ){
        if (!"1".equals(driver.getDriveStatus()) && !"2".equals(driver.getDriveStatus())) {
            return R.error(-2,"司机不是可接单状态!");
        }
        int status = driverService.realTimeLocation(driver,longitude,latitude,address);
        if (status == 1) {
           return R.ok("成功更新位置!");
        } else {
           return R.error(-1,"更新位置失败!");
        }

    }

    /**
     * 司机收车，停止接单
     */
    @PostMapping("closeCar")
    public R closeCar(@LoginDriver SjDriverEntity driver){
        //避免重复收车
        if(driver.getDriveStatus() != null && "0".equals(driver.getDriveStatus())) {
            return R.error(-2,"司机已经收车了!");
        }
        String paraForSign = "ids=" + driver.getGaoId() + "&key=" + QwjGlobal.AUTONAVI_WEB_KEY + "&tableid=" + QwjGlobal.AUTONAVI_HTTP_TABLE_ID;
        String privateKey = QwjGlobal.AUTONAVI_WEB_PRIVATE_KEY;
        String sig = MD5Util.MD5Encode(paraForSign + privateKey, "utf-8");

        Map<String, String> paraMap = new HashMap<String, String>();
        paraMap.put("ids", driver.getGaoId());
        paraMap.put("key", QwjGlobal.AUTONAVI_WEB_KEY);
        paraMap.put("tableid", QwjGlobal.AUTONAVI_HTTP_TABLE_ID);
        paraMap.put("sig", sig);

        //发送 POST 请求
        String sr = HttpUtil.sendPost(QwjGlobal.AUTONAVI_HTTP_DATA_DELETE_URL, paraMap);
        Map<String, Object> resultMap = QmJsonUtils.parseJSON2Map(sr);
        int status = Integer.valueOf(String.valueOf(resultMap.get("status"))).intValue();
        if (status == 1) {
            driver.setGaoId(null);
            driver.setDriveStatus("0"); //设置1代表出车，等待订单状态
            driver.setRegistrationId(null);
            driverService.update(driver);
            return R.ok("收车成功!");
        } else {
            return R.error(-1,"收车失败!");
        }

    }

    /**
     * 司机完成配送订单(暂停使用)
     */
    @PostMapping("completePsOrder")
    public R completePsOrder(@LoginDriver SjDriverEntity driver, String ordernum, BigDecimal extraCharge, String extraChargeNote){
        PsOrderEntity psOrder = psOrderService.queryByOrderNum(ordernum);
        if (psOrder == null) {
            return R.error(-1,"订单不存在!");
        }
        if (!driver.getId().equals(psOrder.getDriverId())) {
            return R.error(-2,"非法操作,与订单司机不匹配!");
        }
        driverService.completedPsOrder(psOrder,driver,extraCharge,extraChargeNote); //更加符合面向对象思想

        return R.ok();
    }

    /**
     * 司机查询进行中的配送订单
     */
    @PostMapping("queryOnGoingPsOrder")
    public R queryOnGoingPsOrder(@LoginDriver SjDriverEntity driver){
        List<PsOrderEntity> psOrders = psOrderService.driverQueryOnGoingPsOrder(driver.getId());
        if (psOrders != null ){
            for (PsOrderEntity psOrder:psOrders) {
                List<Map<String,Object>> destinationList = psOrderRouteSectionService.queryDestinationsByOrderNum(psOrder.getOrdernum());
                JSONArray destinationJsonArray = JSONArray.parseArray(JSON.toJSONString(destinationList));
                psOrder.setDestinationJsonArray(destinationJsonArray);
            }
        }
        return R.ok().put("onGoingPsOrders",psOrders);
    }

    /**
     * 司机查询已结束的配送订单(原已完成接口)
     */
    @PostMapping("queryCompletedPsOrder")
    public R queryCompletedPsOrder(@LoginDriver SjDriverEntity driver){
        List<PsOrderEntity> psOrders = psOrderService.driverQueryCompletedPsOrder(driver.getId());
        if (psOrders != null ){
            for (PsOrderEntity psOrder:psOrders) {
                List<Map<String,Object>> destinationList = psOrderRouteSectionService.queryDestinationsByOrderNum(psOrder.getOrdernum());
                JSONArray destinationJsonArray = JSONArray.parseArray(JSON.toJSONString(destinationList));
                psOrder.setDestinationJsonArray(destinationJsonArray);
            }
        }
        return R.ok().put("completedPsOrders",psOrders);
    }

    /**
     * 司机查看已取消的配送订单(整合到已结束里)
     */
    @PostMapping("queryCancelPsOrder")
    public R queryCancelPsOrder(@LoginDriver SjDriverEntity driver){
        List<PsOrderEntity> psOrders = psOrderService.driverQueryCancelPsOrder(driver.getId());
        return R.ok().put("cancelPsOrder",psOrders);
    }

    /**
     * 司机接单
     */
    @PostMapping("receivePstOrder")
    public R receivePstOrder(@LoginDriver SjDriverEntity driver,String ordernum,String longitude, String latitude){
        PsOrderEntity psOrder  = psOrderService.queryByOrderNum(ordernum);
        if (psOrder == null) {
            return R.error(-1,"订单不存在!");
        }
        if (psOrder.getDriverId() != null) {
            return R.error(-4,"订单已有人接了!");
        }
        if ("0".equals(psOrder.getOrderStatus())) {
//            //接单人ID
//            psOrder.setDriverId(driver.getId());
//            //接单人姓名
//            psOrder.setDriverName(driver.getRealname());
//            //接单人电话
//            psOrder.setDriverTel(driver.getUsername());
//            //订单状态 已经接单
//            psOrder.setOrderStatus("1");
//            //todo 给当前订单记录加锁，防止并发访问更改数据库
//            //删除高德云位置信息
//            int operation = AutoNaviUtils.DeleteDataById(driver.getGaoId());
//            if (operation == 1) {
//                driver.setGaoId(null);
//                driver.setDriveStatus("2");
//                driverService.update(driver);
//            } else {
//                return R.error(-4,"接单失败,删除高德云位置失败!");
//            }
//            //接单时间
//            psOrder.setReceiveTime(new Date());
//            psOrderService.update(psOrder);
//            //todo 给订单记录解锁，防止并发访问更改数据库
//            UserEntity user = userService.queryObject(psOrder.getUserId());
//            QmSendPush.sendOrderReceivedToUser(user.getRegistrationId(),psOrder);
            driverService.receivePstOrder(psOrder,driver,longitude,latitude);

        } else {
            return R.error(-3,"订单为不可接状态!");
        }

        return R.ok().put("psOrder",psOrder);
    }

    /**
     *  司机出发，开始计算里程数
     */
    @PostMapping("startCalculateMileage")
    public R startCalculateMileage(@LoginDriver SjDriverEntity driver,String ordernum,String curLng,String curLat){
        PsOrderEntity psOrder  = psOrderService.queryByOrderNum(ordernum);
        if (psOrder == null) {
            return R.error(-1,"订单不存在!");
        }
        driverService.startCalculateMileage(psOrder,curLng,curLat);

        return R.ok("成功出发!");
    }

    /**
     * 实时更新已经行驶的里程(后台)
     */
    @PostMapping("calculateMileageByBackGround")
    public R calculateMileageByBackGround(@LoginDriver SjDriverEntity driver,String ordernum,String curLng,String curLat,String address){
        PsOrderEntity psOrder = psOrderService.queryByOrderNum(ordernum);
        if ( psOrder == null ) {
            return R.error(-1,"订单不存在!");
        }
//        if(curLng.equals(psOrder.getCurLng()) && curLat.equals(psOrder.getCurLat())){
//            return R.error(-3,"还在原地");
//        }
        driverService.realTimeLocationUpdatePsOrder(driver,psOrder,curLng,curLat,address);

        return R.ok();
    }

    /**
     * 实时更新已经行驶的里程(前台)
     */
    @PostMapping("calculateMileageByForeGroud")
    public R calculateMileageByForeGroud(@LoginDriver SjDriverEntity driver,String ordernum,String curLng,String curLat,String mileage){
        PsOrderEntity psOrder = psOrderService.queryByOrderNum(ordernum);
        if ( psOrder == null ) {
            return R.error(-1,"订单不存在!");
        }
        psOrder.setCurLng(curLng);
        psOrder.setCurLat(curLat);
        psOrder.setRealdistance(mileage);
        psOrderService.update(psOrder);


        return R.ok();
    }

    /**
     * 司机取消订单
     */
    @PostMapping("cancelPsOrder")
    public R cancelPsOrder(@LoginDriver SjDriverEntity driver,String ordernum){
        PsOrderEntity psOrder = psOrderService.queryByOrderNum(ordernum);
        if ( psOrder == null ) {
            return R.error(-1,"订单不存在!");
        }
        driverService.cancelPsOrder(psOrder,driver);

        return R.ok();
    }

    /**
     * 司机查推送配送订单记录
     */
    @PostMapping("queryPushRecords")
    public R queryPushRecords(@LoginDriver SjDriverEntity driver){
        List<PsOrderEntity> psOrders = psOrderService.driverQueryPushRecords(driver.getUsername());
        return R.ok().put("pushRecords",psOrders);
    }

    /**
     * 司机到达发货地,开始装货
     */
    @PostMapping("arriveStart")
    public R arriveStart(@LoginDriver SjDriverEntity driver,String ordernum){
        PsOrderEntity psOrder = psOrderService.queryByOrderNum(ordernum);
        if ( psOrder == null ) {
            return R.error(-1,"订单不存在!");
        }
        if (!driver.getId().equals(psOrder.getDriverId())) {
            return R.error(-3,"非法操作,与订单司机不匹配!");
        }
        driverService.arriveStart(psOrder);

        return R.ok();
    }

    /**
     * 司机到达目的地,开始卸货
     */
    @PostMapping("arriveEnd")
    public R arriveEnd(@LoginDriver SjDriverEntity driver,String ordernum){
        PsOrderEntity psOrder = psOrderService.queryByOrderNum(ordernum);
        if ( psOrder == null ) {
            return R.error(-1,"订单不存在!");
        }
        if (!driver.getId().equals(psOrder.getDriverId())) {
            return R.error(-3,"非法操作,与订单司机不匹配!");
        }
        driverService.arriveEnd(psOrder);

        return R.ok();
    }

    /**
     * 上传照片
     * @param file 传body参数里面要指定是file
     * @param driver 登录的用户，注解根据传的tokne处理，不用传参
     * @param ordernum 订单号
     * @return
     */
    @PostMapping(value = "/uploadPsOrderImg", headers = {"Content-Type=multipart/form-data"})
    public R uploadPsOrderImg(@RequestBody MultipartFile file, @LoginDriver SjDriverEntity driver, String ordernum) {

        String filePath = "";
        String filename = "";
        // 判断文件是否为空
        if (!file.isEmpty()) {
            if (file.getSize() > 10240000) {
                throw new RRException("上传失败：文件大小不能超过10M");
            }
            PsOrderEntity psOrder = psOrderService.queryByOrderNum(ordernum);
            try {
                //提取后缀
                String postfix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                    filename = driver.getId()+"_face_" + DateUtils.format(new Date(), "yyyyMMddHHmmss")+RandomUtils.generateString(4) + postfix;
                //设置订单装货照片
                psOrder.setLoadingImg(filename);
                // 文件保存路径
                filePath = ROOT_PsImages+ filename;
                File saveDir = new File(filePath);
                //判断目标文件所在的目录是否存在
                if (!saveDir.getParentFile().exists()) {
                    //如果目标文件所在的目录不存在，则创建父目录
                    saveDir.getParentFile().mkdirs();
                }
                // 转存文件
                file.transferTo(saveDir);
                psOrderService.update(psOrder);
            } catch (Exception e) {
                throw new RRException("文存储异常！");
            }
        } else {
            throw new RRException("上传失败:请添加上传文件！");
        }

        return R.ok();//已记录就不用返回图片路径，有专门的访问接口
    }

    /**
     * 上传照片
     * @param file 传body参数里面要指定是file
     * @param driver 登录的司机，注解根据传的tokne处理，不用传参
     * @param type 传的文件类型, 默认0，表示上传头像
     * @return
     */
    @PostMapping(value = "/uploadImg", headers = {"Content-Type=multipart/form-data"})
    public R uploadImg(@RequestBody MultipartFile file, @LoginDriver SjDriverEntity driver, String type) {

        String filePath = "";
        String filename = "";
        // 判断文件是否为空
        if (!file.isEmpty()) {
            if (file.getSize() > 10240000) {
                throw new RRException("上传失败：文件大小不能超过10M");
            }
            //判断是否上传过头像
            if (driver.getAvatar() != null) {
                File fileToDelete = new File(ROOT+driver.getAvatar());
                if (fileToDelete.exists() && fileToDelete.isFile()) {
                    fileToDelete.delete();
                }
            }
            try {
                //提取后缀
                String postfix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                if("0".equals(type)){
                    filename = driver.getId()+"_face_" + DateUtils.format(new Date(), "yyyyMMddHHmmss")+RandomUtils.generateString(4) + postfix;
                    driver.setAvatar(filename);
                }else{ //除了身份证以外的上传图片
                    filename = driver.getId()+"_bl_" + DateUtils.format(new Date(), "yyyyMMddHHmmss")+RandomUtils.generateString(4) + postfix;
//                        user.setBusinessLicence(filename);
                }
                driverService.update(driver);
                // 文件保存路径
                filePath = ROOT+ filename;
                File saveDir = new File(filePath);
                //判断目标文件所在的目录是否存在
                if (!saveDir.getParentFile().exists()) {
                    //如果目标文件所在的目录不存在，则创建父目录
                    saveDir.getParentFile().mkdirs();
                }
                // 转存文件
                file.transferTo(saveDir);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            throw new RRException("上传失败:请添加上传文件！");
        }
//        System.out.println("filePath:" + filePath);

        return R.ok();//.put("fileId",ossEntity.getId());
    }

    /**
     * 卸货完毕,计算订单价格
     */
    @PostMapping("completeUnloading")
    public R completeUnloading(@LoginDriver SjDriverEntity driver,String ordernum){
        PsOrderEntity psOrder = psOrderService.queryByOrderNum(ordernum);
        if (psOrder == null) {
            return R.error(-1,"订单不存在!");
        }
        if (!driver.getId().equals(psOrder.getDriverId())) {
            return R.error(-3,"非法操作,与订单司机不匹配!");
        }
        PsOrderEntity psOrderR  = driverService.completeUnloading(psOrder,driver);

        return R.ok().put("psOrder",psOrderR);
    }

    /**
     * 修改价格
     */
    @PostMapping("modifyTotalPrice")
    public R modifyTotalPrice(@LoginDriver SjDriverEntity driver,String ordernum,BigDecimal extraCharge, String extraChargeNote){
        PsOrderEntity psOrder = psOrderService.queryByOrderNum(ordernum);
        if (psOrder == null) {
            return R.error(-1,"订单不存在!");
        }
        if (!driver.getId().equals(psOrder.getDriverId())) {
            return R.error(-2,"非法操作,与订单司机不匹配!");
        }
        PsOrderEntity psOrderR = driverService.modifyTotalPrice(psOrder,extraCharge,extraChargeNote);

        return R.ok().put("psOrder",psOrderR);
    }

    /**
     * 司机发起收费
     */
    @PostMapping("goToCharge")
    public R goToCharge(@LoginDriver SjDriverEntity driver,String ordernum){
        PsOrderEntity psOrder = psOrderService.queryByOrderNum(ordernum);
        if (psOrder == null) {
            return R.error(-1,"订单不存在!");
        }
        driverService.goToCharge(psOrder);

        return R.ok();
    }

    /**
     * 司机确认收到现金
     */
    @PostMapping("confirmCash")
    public R confirmCash(@LoginDriver SjDriverEntity driver,String ordernum){
        PsOrderEntity psOrder = psOrderService.queryByOrderNum(ordernum);
        if (psOrder == null) {
            return R.error(-1,"订单不存在!");
        }
        if (!driver.getId().equals(psOrder.getDriverId())) {
            return R.error(-3,"非法操作,与订单司机不匹配!");
        }
        driverService.confirmCash(psOrder);

        return R.ok();
    }

    /**
     * 司机暂不收费接口
     */
    @PostMapping("zbsfy")
    public R zbsfy(@LoginDriver SjDriverEntity driver,String ordernum,String customerName,
                        String deliverNo,String zbsfyy){
        PsOrderEntity psOrder = psOrderService.queryByOrderNum(ordernum);
        if (psOrder == null) {
            return R.error(-1,"订单不存在!");
        }
        if (!driver.getId().equals(psOrder.getDriverId())) {
            return R.error(-3,"非法操作,与订单司机不匹配!");
        }
        psOrder.setCustomerName(customerName); //合作（签约）单位
        psOrder.setDeliverNo(deliverNo);       //送货单号
        psOrder.setZbsfyy(zbsfyy);             //暂不收费原因（可选）
        psOrder.setOrderStatus("10");          //设订单状态为10 暂不收费
        driverService.zbsfy(psOrder);

        return R.ok();
    }

    /**
     * 查询我的界面信息接口
     */
    @PostMapping("queryMineInfo")
    public R queryMineInfo(@LoginDriver SjDriverEntity driver){
        Map<String,Object> mineInfo = driverService.queryMineInfo(driver.getId());

        return R.ok().put("mineInfo",mineInfo);
    }

    /**
     * 司机修改目的地
     */
    @PostMapping("modifyDestination")
    public R modifyDestination(@LoginDriver SjDriverEntity driver,String ordernum,String psOrderRouteSections){
        PsOrderEntity psOrder = psOrderService.queryByOrderNum(ordernum);
        if (psOrder == null) {
            return R.error(-1,"订单不存在!");
        }
        if (!driver.getId().equals(psOrder.getDriverId())) {
            return R.error(-3,"非法操作,与订单司机不匹配!");
        }

        driverService.modifyDestination(psOrder,driver,psOrderRouteSections);

        return R.ok().put("psOrder",psOrder);
    }

    /**
     * 查询分月统计司机收入接口
     */
    @PostMapping("queryIncomeGroupByMonth")
    public R queryIncomeGroupByMonth(@LoginDriver SjDriverEntity driver){
        List<Map<String,Object>> incomeInfo = driverService.queryIncomeGroupByMonth(driver.getId());

        return R.ok().put("incomeInfo",incomeInfo);
    }

    /**
     * 按输入的具体月份查询当月的收入情况
     */
    @PostMapping("queryIncomeByIuputMonth")
    public R queryIncomeByIuputMonth(@LoginDriver SjDriverEntity driver,String month){
        Map<String,Object> incomeInfoMonth = driverService.queryIncomeByIuputMonth(driver.getId(),month);
        //按月份查询司机收入明细
        List<Map<String,Object>> incomeDetailInfo = driverService.queryIncomeDetailByIuputMonth(driver.getId(),month);
        return R.ok().put("incomeInfoMonth",incomeInfoMonth).put("incomeDetailInfo",incomeDetailInfo);
    }

    /**
     * 司机余额界面接口
     */
    @PostMapping("myBalance")
    public R myBalance(@LoginDriver SjDriverEntity driver){
        //查询余额相关的数据
        Map<String,Object> balanceInfo = driverService.queryBalanceInfo(driver.getId());
//        //查询司机最近5笔明细
//        List<Map<String,Object>> incomeDetailInfo = driverService.queryIncomeDetail(driver.getId());
        //提现记录
        Map<String,Object> param = new HashedMap();
        param.put("driverId",driver.getId());
        List<SjTixianEntity> sjTixianEntities = sjTixianService.queryList(param);

        return R.ok().put("balanceInfo",balanceInfo).put("sjTixianEntities",sjTixianEntities);
    }

    /**
     * 司机申请提现
     */
    @PostMapping("applyToCash")
    public R applyToCash(@LoginDriver SjDriverEntity driver,BigDecimal money){
        if (money == null || money.compareTo(new BigDecimal("0")) <= 0) {
            R.error(-3,"提现金额为空或为0为负!");
        }
//        if (bankCardNo == null || "".equals(bankCardNo)) {
//            R.error(-4,"银行卡号为null或为\"\"!");
//        }
        if (driver.getAvailableAmount().compareTo(money) == -1) { //可提现金额比提现金额小
            return R.error(-1,"超过可提现金额!");
        }
        SjTixianEntity sjTixianEntity = new SjTixianEntity();
        sjTixianEntity.setProposerId(driver.getId()); //提现人id
        sjTixianEntity.setMoney(money);               //提现金额
        BigDecimal actualPoundage;
//        if (money.multiply(new BigDecimal("0.02")).compareTo(new BigDecimal("60")) == 1) { //若2%手续费大于60
//            actualPoundage = new BigDecimal("60");
//        } else {
//            actualPoundage = money.multiply(new BigDecimal("0.02"));
//        }
        PsParamSetEntity psParamSet = psParamSetService.queryObject((long)1); //获取当前提现抽成比例
        actualPoundage = money.multiply(psParamSet.getParaValue());
        sjTixianEntity.setPoundage(actualPoundage);   //手续费
        sjTixianEntity.setActualAccount(money.subtract(actualPoundage)); //实际到账金额
//        sjTixianEntity.setBankCardNo(bankCardNo);     //银行卡号
        sjTixianEntity.setCreateTime(new Date());
        sjTixianService.save(sjTixianEntity);

        //司机余额扣掉提现额
        driver.setBalance(driver.getBalance().subtract(money));
        driverService.update(driver);

        return R.ok("提交成功").put("sjTixianEntity",sjTixianEntity);
    }

    /**
     * 司机查看提现记录
     */
    @PostMapping("queryTxRecord")
    public R queryTxRecord(@LoginDriver SjDriverEntity driver){
        Map<String,Object> param = new HashedMap();
        param.put("driverId",driver.getId());
        List<SjTixianEntity> sjTixianEntities = sjTixianService.queryList(param);

        return R.ok().put("sjTixianEntities",sjTixianEntities);
    }

    /**
     * 司机查询订单目的地
     */
    @PostMapping("queryPsOrderDes")
    public R queryPsOrderDes(@LoginDriver SjDriverEntity driver,String ordernum){
        List<Map<String,Object>> destinationList = psOrderRouteSectionService.queryDestinationsByOrderNum(ordernum);

        return R.ok().put("destinationList",destinationList);
    }

    /**
     *  司机到达第几个目的地(开始卸货)
     */
    @PostMapping("arriveDesByNum")
    public R arriveDesByNum(@LoginDriver SjDriverEntity driver,String ordernum,Integer arriveDesNum){
        PsOrderEntity psOrder = psOrderService.queryByOrderNum(ordernum);
        if (psOrder == null) {
            return R.error(-1,"订单不存在!");
        }
        if (!driver.getId().equals(psOrder.getDriverId())) {
            return R.error(-3,"非法操作,与订单司机不匹配!");
        }
        driverService.arriveDesByNum(psOrder,arriveDesNum);

        return R.ok();
    }

    /**
     * 司机从第几个目的地卸货完成(卸货完成开始出发)
     */
    @PostMapping("startDesByNum")
    public R startDesByNum(@LoginDriver SjDriverEntity driver,String ordernum,Integer arriveDesNum){
        PsOrderEntity psOrder = psOrderService.queryByOrderNum(ordernum);
        if (psOrder == null) {
            return R.error(-1,"订单不存在!");
        }
        if (!driver.getId().equals(psOrder.getDriverId())) {
            return R.error(-3,"非法操作,与订单司机不匹配!");
        }
        PsOrderEntity psOrder2 = driverService.startDesByNum(psOrder,arriveDesNum);

        return R.ok().put("psOrder",psOrder);
    }

    /**
     * 司机查询订单跟踪
     */
    @PostMapping("queryPsOrderLogistics")
    public R queryPsOrderLogistics(@LoginDriver SjDriverEntity driver, String ordernum){
        Map<String,Object> param = new HashMap<>();
        param.put("orderNum",ordernum);
        List<PsOrderLogisticsRecordEntity> psOrderLogisticsRecords = psOrderLogisticsRecordService.queryList(param);

        return R.ok().put("psOrderLogisticsRecords",psOrderLogisticsRecords);
    }

    @PostMapping("queryPsOrderByOrderNum")
    public R queryPsOrderByOrderNum(@LoginDriver SjDriverEntity driver,String ordernum){
        PsOrderEntity psOrder = psOrderService.queryByOrderNum(ordernum);

        return R.ok().put("psOrder",psOrder);
    }

}
